package com.his.config;


import com.his.bean.DzmHisMember;
import com.his.service.DzmHisMemberService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

public class MyRealm extends AuthorizingRealm {


    @Autowired
    DzmHisMemberService dzmHisMemberService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof UsernamePasswordToken;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("我是shiro的realm认证");
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
        String username = usernamePasswordToken.getUsername();

        char[] password = usernamePasswordToken.getPassword();
        String strpassword = new String(password);


        //从数据库取出来的用户名
        DzmHisMember dzmHisMember = dzmHisMemberService.getUserNameAndPassWord(username, strpassword);

        //把前台传过来的username和 数据库中的username做对比
        if (!username.equals(dzmHisMember.getUserName())) {
            throw new UnknownAccountException();
        } else if (!strpassword.equals(dzmHisMember.getPassWord())) {
            throw new IncorrectCredentialsException();
        }
        DzmHisMember dzmHisMember1 = new DzmHisMember();
        dzmHisMember1.setUserName(dzmHisMember.getUserName());
        dzmHisMember1.setPassWord(dzmHisMember.getPassWord());
//                                                 第二个参数代表你数据库的密码，shiro帮你验证
        return new SimpleAuthenticationInfo(dzmHisMember1, dzmHisMember1.getPassWord(), getName());
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("我是shiro的realm授权");

        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();

        Subject subject = SecurityUtils.getSubject();

        DzmHisMember user = (DzmHisMember) subject.getPrincipal();
//
//        String right = user.getRight();
//        String[] split = right.split(",");
//        for (String s : split) {
//            simpleAuthorizationInfo.addStringPermission(s);
//        }

        return simpleAuthorizationInfo;
    }
}
